package org.cid54.android.jshopper.dao.impl;

import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cid54.android.jshopper.dao.DaoCallBackMethod;
import org.cid54.android.jshopper.dao.ItemDao;
import org.cid54.android.jshopper.data.CsvFetcher;
import org.cid54.android.jshopper.data.impl.CsvFetcherImpl;

/**
 *
 * @author fgo
 */
public class ItemDaoImpl implements ItemDao {

    private CsvFetcher fetcher = new CsvFetcherImpl();

    private static final String itemsSubUrl = "items";
    
    public void getAllItemNames(final DaoCallBackMethod<List<String>> callBack) {

        AsyncTask<Void, Void, List<String>> task = new AsyncTask<Void, Void, List<String>>() {

            @Override
            protected List<String> doInBackground(Void... arg0) {

                List<String> resultL = new ArrayList<String>();

                List<String[]> strings = fetcher.getData(itemsSubUrl);

                for (String[] line : strings) {

                    resultL.add(line[0]);

                }

                return resultL;
            }

            @Override
            protected void onPostExecute(List<String> result) {
                super.onPostExecute(result);
                callBack.execute(result);
            }
        };

        task.execute();

    }

    public void addItem(String itemName, final DaoCallBackMethod<Boolean> callBack) {
        AsyncTask<String, Void, Boolean> task = new AsyncTask<String, Void, Boolean>() {

            @Override
            protected Boolean doInBackground(String... arg0) {

                String itemName = arg0[0];

                Map<String, String> argsMap = new HashMap<String, String>();

                argsMap.put("name", itemName);

                return fetcher.postData("items/add", argsMap);
            }

            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
                callBack.execute(result);
            }
        };

        task.execute(itemName);
    }
}
